package sys_serv

import (
	"strconv"
	"strings"
	"ubt-aio-service/app/mod/sys_mod"
	"ubt-aio-service/app/pkg/db"
	"ubt-aio-service/app/utils"
)

type sysFile struct{}

var SysFileServ = sysFile{}

// Add 新增文件
func (s *sysFile) Add(req *sys_mod.SysFileAddReq) *utils.ResJson {
	sqlStr := `INSERT INTO sys_file(file_id, file_name, file_size, kind, file_ext, real_path, visit_url, add_time, upd_time) 
		VALUES ($1, $2, $3, $4, $5, $6, $7, EXTRACT(epoch FROM NOW()), EXTRACT(epoch FROM NOW()))`
	return db.CudData(sqlStr, req.FileId, req.FileName, req.FileSize, req.Kind, req.FileExt, req.RealPath, req.VisitUrl)
}

// UpdName 修改文件名称
func (s *sysFile) UpdName(req *sys_mod.SysFileNameReq) *utils.ResJson {
	sqlStr := "UPDATE sys_file SET file_name=$1, upd_time=EXTRACT(epoch FROM NOW()) WHERE file_id=$2"
	return db.CudData(sqlStr, req.FileName, req.FileId)
}

// UpdType 修改文件类型
func (s *sysFile) UpdType(req *sys_mod.SysFileTypeReq) *utils.ResJson {
	var (
		param []any
		q     string
		n     = 1
	)
	param = append(param, req.FileType)
	idList := strings.Split(req.FileIds, ",")
	for _, curId := range idList {
		n++
		q += "$" + strconv.Itoa(n) + ","
		param = append(param, curId)
	}
	q = q[:len(q)-1]
	sqlStr := "UPDATE sys_file SET file_type=$1, upd_time=EXTRACT(epoch FROM NOW()) WHERE file_id IN (" + q + ")"
	return db.CudData(sqlStr, param...)
}

// Delete 删除文件
func (s *sysFile) Delete(fileId string) *utils.ResJson {
	sqlStr := "SELECT kind, real_path FROM sys_file WHERE file_id=$1"
	if res := db.GetOne(sqlStr, fileId); res.Code == utils.Succeed.Code {
		utils.ImgProc.RemoveFile(res.Data.(map[string]any)["kind"].(int64), res.Data.(map[string]any)["realPath"].(string))
	}
	sqlStr = "DELETE FROM sys_file WHERE file_id=$1"
	return db.CudData(sqlStr, fileId)
}

// Deletes 批量删除文件
func (s *sysFile) Deletes(fileIds string) *utils.ResJson {
	var (
		param []any
		q     string
		n     = 0
	)
	idList := strings.Split(fileIds, ",")
	for _, curId := range idList {
		n++
		q += "$" + strconv.Itoa(n) + ","
		param = append(param, curId)
	}
	q = q[:len(q)-1]
	sqlStr := "SELECT kind, real_path FROM sys_file WHERE file_id IN (" + q + ")"
	if res := db.GetAll(sqlStr, param...); res.Code == utils.Succeed.Code {
		for _, path := range res.Data.([]map[string]any) {
			utils.ImgProc.RemoveFile(path["kind"].(int64), path["realPath"].(string))
		}
	}
	sqlStr = "DELETE FROM sys_file WHERE file_id IN (" + q + ")"
	return db.CudData(sqlStr, param...)
}

// One 获取文件详情
func (s *sysFile) One(fileId string) *utils.ResJson {
	sqlStr := `SELECT a.file_id, a.file_name, a.file_size, a.kind, a.file_ext, a.file_type, b.dict_name, b.dict_code, 
		a.visit_url, a.add_time 
		FROM sys_file a 
		LEFT JOIN sys_dict b ON b.kind=2 AND a.file_type=b.dict_id 
		WHERE a.file_id=$1`
	return db.GetOne(sqlStr, fileId)
}

// Count 获取文件数量
func (s *sysFile) Count(req *sys_mod.SysFilePageReq) *utils.ResJson {
	sqlStr := "SELECT COUNT(1) AS nums FROM sys_file WHERE 1=1"
	var param []any
	var n = 0
	if req.Keywords != "" {
		sqlStr += " AND ("
		nameArr := strings.Split(req.Keywords, " ")
		for _, name := range nameArr {
			sqlStr += "file_name LIKE '%'||$" + strconv.Itoa(n+1) + "||'%' OR " +
				"file_ext LIKE '%'||$" + strconv.Itoa(n+2) + "||'%' OR "
			param = append(param, name)
			param = append(param, name)
			n += 2
		}
		sqlStr = sqlStr[:len(sqlStr)-4]
		sqlStr += ")"
	}
	if req.Kind > 0 {
		n++
		sqlStr += " AND kind=$" + strconv.Itoa(n)
		param = append(param, req.Kind)
	}
	if req.FileType != "" {
		n++
		sqlStr += " AND file_type=$" + strconv.Itoa(n)
		param = append(param, req.FileType)
	}
	if req.BeginTime > 0 {
		n++
		sqlStr += " AND add_time>=$" + strconv.Itoa(n)
		param = append(param, req.BeginTime)
	}
	if req.EndTime > 0 {
		n++
		sqlStr += " AND add_time<=$" + strconv.Itoa(n)
		param = append(param, req.EndTime)
	}
	if res := db.GetOne(sqlStr, param...); res.Code == utils.Succeed.Code && res.Data.(map[string]any)["nums"].(int64) > 0 {
		return res
	}
	return utils.NoData
}

// Page 获取文件分页列表
func (s *sysFile) Page(req *sys_mod.SysFilePageReq) *utils.ResJson {
	sqlStr := "SELECT a.file_id, a.file_name, a.file_ext, a.kind, b.dict_name, b.dict_code, a.visit_url, a.add_time " +
		"FROM sys_file a LEFT JOIN sys_dict b ON b.kind=2 AND a.file_type=b.dict_id WHERE 1=1"
	var param []any
	var n = 0
	if req.Keywords != "" {
		sqlStr += " AND ("
		nameArr := strings.Split(req.Keywords, " ")
		for _, name := range nameArr {
			sqlStr += "a.file_name LIKE '%'||$" + strconv.Itoa(n+1) + "||'%' OR " +
				"a.file_ext LIKE '%'||$" + strconv.Itoa(n+2) + "||'%' OR "
			param = append(param, name)
			param = append(param, name)
			n += 2
		}
		sqlStr = sqlStr[:len(sqlStr)-4]
		sqlStr += ")"
	}
	if req.Kind > 0 {
		n++
		sqlStr += " AND a.kind=$" + strconv.Itoa(n)
		param = append(param, req.Kind)
	}
	if req.FileType != "" {
		n++
		sqlStr += " AND a.file_type=$" + strconv.Itoa(n)
		param = append(param, req.FileType)
	}
	if req.BeginTime > 0 {
		n++
		sqlStr += " AND a.add_time>=$" + strconv.Itoa(n)
		param = append(param, req.BeginTime)
	}
	if req.EndTime > 0 {
		n++
		sqlStr += " AND a.add_time<=$" + strconv.Itoa(n)
		param = append(param, req.EndTime)
	}
	sqlStr += " ORDER BY a.upd_time DESC LIMIT $" + strconv.Itoa(n+1) + " OFFSET $" + strconv.Itoa(n+2)
	param = append(param, req.Limit)
	param = append(param, req.Offset)
	return db.GetAll(sqlStr, param...)
}

// GetRealPath 获取文件物理路径
func (s *sysFile) GetRealPath(fileId string) *utils.ResJson {
	sqlStr := "SELECT real_path, file_name||file_ext AS file_name FROM sys_file WHERE file_id=$1"
	return db.GetOne(sqlStr, fileId)
}
